package com.example.twotwo_project;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.widget.Toast;


public class NaverParser {
	private String key1;
	ArrayList<LocalData> ldata;
	
	NaverParser(String key){
		this.key1=key;
	}
	
	public ArrayList<LocalData> getBookData2(final String info,final int count,final int start){ // 검색값 , 보여주는 갯수, 시작위치
		ldata=new ArrayList<LocalData>();
		
		LocalData item=null;
		
		String m_searchinfo="";
		
		try{
			m_searchinfo=URLEncoder.encode(info, "UTF-8"); // 인코딩작업
		} catch(UnsupportedEncodingException e1){
			e1.printStackTrace();
		}
		
		try{
			URL text= new URL(
					"http://openapi.naver.com/search?key=" + key1 + "&query="
					+ m_searchinfo + "&display=" + count 
					+ "&start=" + start + "&target=local"); // 네이버 api 지역검색
			                                               //
			XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
			XmlPullParser parser=parserCreator.newPullParser();
			
			parser.setInput(text.openStream(),null);
			
			Log.i("NET", "Parsing...");
			
			// 
			int parseEvent = parser.getEventType();
			while(parseEvent != XmlPullParser.END_DOCUMENT){
				
				switch(parseEvent){
				
				case XmlPullParser.START_TAG:
					String tag=parser.getName();
					
					if(tag.compareTo("title")==0)
					{
						item=new LocalData();
						Spanned mtitle = Html.fromHtml(parser.nextText());
						String titlesrc = mtitle.toString();
						item.title=titlesrc;
						//Log.i("NET","START...");
					}
					
					if(tag.compareTo("telephone")==0)
					{
						String phonesrc=parser.nextText();
						item.telephone=phonesrc;
					}
					if(tag.compareTo("roadAddress")==0)
					{
						String adrsrc=parser.nextText();
						item.roadAddress=adrsrc;
						ldata.add(item);
					}
					break;
				}
				parseEvent=parser.next();
				
				//�.. END_DOCUMENT�϶�����..
			}
			Log.i("NET","End...");
		} catch(Exception e)
		{
			Log.i("NET","Parsing fail");
		}
		return ldata;
	}
	
	
}
